package com.pactera.miyuangroup.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.pactera.miyuangroup.common.Constants;
import com.pactera.miyuangroup.db.entity.GoodsInfo;
import com.pactera.miyuangroup.db.entity.Replenishment;
import com.pactera.miyuangroup.db.entity.VendorInfo;
import com.pactera.miyuangroup.db.entity.VendorPassageway;
import com.pactera.miyuangroup.db.mapper.ReplenishmentMapper;
import com.pactera.miyuangroup.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.pactera.miyuangroup.vo.convertor.ReplenishmentConvert;
import com.pactera.miyuangroup.vo.request.app.AppAddReplenishmentReq;
import com.pactera.miyuangroup.vo.request.app.AppReplenishmentReq;
import com.pactera.miyuangroup.vo.request.web.GoodsInfoReques;
import com.pactera.miyuangroup.vo.request.web.ReplenishmentRequest;
import com.pactera.miyuangroup.vo.response.app.AppReplenishmentListRes;
import com.pactera.miyuangroup.vo.response.app.AppReplenishmentRes;
import com.pactera.miyuangroup.vo.response.app.AppSelectVendorPassagewayRes;
import com.pactera.miyuangroup.vo.response.miyuan.*;
import com.pactera.miyuangroup.vo.response.web.GoodsInfoRes;
import com.pactera.miyuangroup.vo.response.web.ReplenishmentRes;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 补货记录 服务实现类
 * </p>
 *
 * @author WangWu
 * @since 2018-04-13
 */
@Service
@Slf4j
public class ReplenishmentServiceImp extends ServiceImpl<ReplenishmentMapper, Replenishment> implements ReplenishmentService {
    @Autowired
    private ReplenishmentConvert replenishmentConvert;

    @Autowired
    private VendorPassagewayService vendorPassagewayService;

    @Autowired
    private GoodsInfoService goodsInfoService;
    @Autowired
    private VendorInfoService vendorInfoService;

    @Autowired
    private MiyuanDataService miyuanDataService;

    @Override
    public Page<ReplenishmentRes> getReplenishmentList(ReplenishmentRequest replenishmentRequest, String org) {

        //验证数据
        EntityWrapper wrapper = new EntityWrapper();

        //organization_id
        if (!Constants.SYS_ROOT.equals(org)) {
            wrapper.eq("`user`.organization_id", org);
        }
        if (StringUtils.isNotBlank(replenishmentRequest.getNumbers())) {
            wrapper.eq("numbers", replenishmentRequest.getNumbers());
        }

        if (StringUtils.isNotBlank(replenishmentRequest.getVendorId())) {
            wrapper.eq("number", replenishmentRequest.getVendorId());
        }

        if (StringUtils.isNotBlank(replenishmentRequest.getControlNumber())) {
            wrapper.eq("control_number", replenishmentRequest.getControlNumber());
        }

        if (StringUtils.isNotBlank(replenishmentRequest.getJobNumber())) {
            wrapper.eq("job_number", replenishmentRequest.getJobNumber());
        }

        //查询数据
        Page<ReplenishmentRes> ReplenishmentLists = new Page<ReplenishmentRes>(replenishmentRequest.getCurrent(), replenishmentRequest.getSize());
        List<ReplenishmentRes> ReplenishmentList = baseMapper.selectReplenishmentList(ReplenishmentLists, wrapper);
        List<ReplenishmentRes> repList = replenishmentConvert.convert2ReplenishmentRes(ReplenishmentList);


        ReplenishmentLists.setRecords(repList);
        return ReplenishmentLists;
    }

    @Override
    public Page<AppReplenishmentRes> getAppReplenishmentList(AppReplenishmentReq appReplenishmentReq, String userId) {
        //验证数据
        EntityWrapper wrapper = new EntityWrapper();
        wrapper.eq("user_id", userId);

        if (StringUtils.isNotBlank(appReplenishmentReq.getParameter())) {
            wrapper.andNew("numbers={0}", appReplenishmentReq.getParameter()).or("number={0}", appReplenishmentReq.getParameter());
        }
        if (null != appReplenishmentReq.getStartTime()) {
            wrapper.ge("replenishment_time", appReplenishmentReq.getStartTime());
        }
        if (null != appReplenishmentReq.getEndTime()) {
            wrapper.le("replenishment_time", appReplenishmentReq.getEndTime());
        }

        Page<AppReplenishmentRes> appReplenishmentResPage = new Page<AppReplenishmentRes>(appReplenishmentReq.getCurrent(), appReplenishmentReq.getSize());

        //查询数据
        List<AppReplenishmentRes> appReplenishmentRes = baseMapper.appSelectReplenishmentList(appReplenishmentResPage, wrapper);


        appReplenishmentResPage.setRecords(appReplenishmentRes);

        return appReplenishmentResPage;
    }


    /*
    * 前端工控号查询补货机信息
    * */
    @Override
    public AppReplenishmentRes getAppVendorInfo(String controlNumber) {
        log.info("开始验证数据");
        EntityWrapper wrapper = new EntityWrapper();

        if (StringUtils.isNotBlank(controlNumber)) {
            wrapper.eq("`vendor`.`control_number`", controlNumber);
        }

        log.info("开始查询数据--查询售货机信息");
        AppReplenishmentRes appReplenishmentRes = baseMapper.appSelectVendorInfo(wrapper);


        log.info("开始查询数据--售货机销售金额");

        MiYuanModel<VendorSaleInfo> vendorSaleInfo = miyuanDataService.getVendorSaleInfo(controlNumber);

        if (vendorSaleInfo.isSuccess()) {
            appReplenishmentRes.setTotalAmount(vendorSaleInfo.getData().getTotalAmount());
        } else {
            appReplenishmentRes.setTotalAmount("0");
        }

        return appReplenishmentRes;
    }

    /*
    * 前端插入补货记录
    * */

    @Override
    public boolean addReplenishmentRes(AppAddReplenishmentReq appAddReplenishmentReq) {
        log.info("开始验证数据");
        if (!StringUtils.isNotBlank(appAddReplenishmentReq.getNumbers()) ||
                !StringUtils.isNotBlank(appAddReplenishmentReq.getVendorId()) ||
                !StringUtils.isNotBlank(appAddReplenishmentReq.getUserId()) ||
                !StringUtils.isNotBlank(appAddReplenishmentReq.getTotalAmount().toString())) {
            log.info("提交参数错误，请检查参数是否为空");
            return false;
        }


        int val = appAddReplenishmentReq.getTotalAmount().compareTo(BigDecimal.ZERO);
        log.info("数据比较结果：{}", val);
        if (val != -1) {
            log.info("总金额不能为负数");

            //PO 转 DO
            Replenishment replenishment = replenishmentConvert.convert2Replenishment(appAddReplenishmentReq);


            Date date = new Date();

            replenishment.setReplenishmentTime(date);

            Integer isInsert = baseMapper.insert(replenishment);

            ReplenishmentInfo replenishmentInfo = new ReplenishmentInfo();
            replenishmentInfo.setControlNumber(appAddReplenishmentReq.getControlNumber());

            replenishmentInfo.setReplenishmentTime(new com.pactera.miyuangroup.util.Date(date).toLongDate());

            if (isInsert == 1) {
                miyuanDataService.postReplenishmentInfo(replenishmentInfo);
                VendorInfo vendorInfo = vendorInfoService.selectById(replenishment.getVendorId());
                vendorInfo.setLastReplenishmentTime(replenishment.getReplenishmentTime());
                vendorInfo.updateById();
            }

            log.info("插入数据返回值：{}", isInsert);

            return true;
        } else {
            log.info("总金额小于0");

        }

        return false;
    }


    /*
    * 待补货清单列表
    * */
    @Override
    public List<AppReplenishmentListRes> getAppNeedReplenishmentList(String userId) {
        //查询该用户的设备
        EntityWrapper wrapper = new EntityWrapper();
        wrapper.eq("`c`.`user_id`", userId);
        List<VendorInfo> vendors = baseMapper.selectVendorByUserID(wrapper);

        if (null == vendors || vendors.size() <= 0) {
            return null;
        }

        //待补信息
        List<AppReplenishmentListRes> infoList = new ArrayList<AppReplenishmentListRes>();
        //查询售货机所有货道售卖信息
        for (VendorInfo vendor : vendors) {
            //查询米源数据-一台售货机销售情况
            MiYuanModel<MiYuanPage<VendorPassagewaySaleInfo>> miYuanModel = miyuanDataService.getVendorPassagewaySaleInfo(vendor.getNumber());
            //是否成功
            boolean flg = !miYuanModel.isSuccess() || miYuanModel.getData() == null || miYuanModel.getData().getRecords() == null && miYuanModel.getData().getRecords().size() <= 0;
            if (flg) {
                continue;
            }
            //循环查询货道
            for (VendorPassagewaySaleInfo vendorP : miYuanModel.getData().getRecords()) {
                //查询货道信息
                EntityWrapper vendorPassagewayWrapper = new EntityWrapper();
                vendorPassagewayWrapper.eq("vendor_id", vendor.getId());
                vendorPassagewayWrapper.eq("passageway_number", Integer.parseInt(vendorP.getChannelNum()));
                VendorPassageway vendorPassageway = vendorPassagewayService.selectOne(vendorPassagewayWrapper);
                if (vendorPassageway == null) {
                    continue;
                }
                //查询对应商品信息
                GoodsInfo goodsInfo = goodsInfoService.selectById(vendorPassageway.getGoodsId());
                if (goodsInfo == null) {
                    continue;
                }
                //查询集合中是否存在
                AppReplenishmentListRes appReplenishmentListRes = infoList.stream().filter(g -> goodsInfo.getId().equals(g.getId())).findFirst().orElse(null);
                //验证集合是否出现相同数据
                if (null == appReplenishmentListRes) {
                    //无相同数据
                    appReplenishmentListRes = new AppReplenishmentListRes();
                    appReplenishmentListRes.setId(goodsInfo.getId());
                    appReplenishmentListRes.setGoodsName(goodsInfo.getName());
                    appReplenishmentListRes.setPicture(goodsInfo.getPicture());
                    appReplenishmentListRes.setNumber(goodsInfo.getNumber());
                    appReplenishmentListRes.setTotal(Integer.parseInt(vendorP.getNumber()));
                    infoList.add(appReplenishmentListRes);
                } else {
                    //累加数量
                    appReplenishmentListRes.setTotal(appReplenishmentListRes.getTotal() + Integer.parseInt(vendorP.getNumber()));
                }
            }


        }
        return infoList;
//
//        List<String> VendorIdList = new ArrayList<String>();
//        for (VendorInfo str : VendorID) {
//            VendorIdList.add(str.getId());
//        }
//
//        if (VendorIdList != null) {
//            EntityWrapper wap = new EntityWrapper();
//            wap.in("`vendor`.`id`", VendorIdList);
//            List<AppSelectVendorPassagewayRes> appSelectVendorPassagewayDO = baseMapper.appSelectVendorPassageway(wap);
//            List<AppReplenishmentListRes> infoList = new ArrayList<AppReplenishmentListRes>();
//
//            //查询售货机
//
//
//            //售货机货道信息
//            for (AppSelectVendorPassagewayRes str : appSelectVendorPassagewayDO) {
//                log.info("售货机编号:{}，货道编号：{}，商品ID：{}", str.getNumber(), str.getPassagewayNumber(), str.getGoodsId());
//
//                int nb = 0;
//                //查询集合中是否存在
//                AppReplenishmentListRes appReplenishmentListRes = infoList.stream().filter(g -> str.getGoodsId().equals(g.getId())).findFirst().orElse(null);
//
//                //查询米源数据
//                MiYuanModel<VendorPassagewaySaleInfo> miYuanModel = miyuanDataService.getVendorPassagewaySaleInfo(str.getNumber(), str.getPassagewayNumber());
//                if (miYuanModel.isSuccess()) {
//                    log.info("货道编号:{}，销售数量：{}", miYuanModel.getData().getChannelNum(), miYuanModel.getData().getNumber());
//                    nb = Integer.parseInt(miYuanModel.getData().getNumber());
//                }
//
//                //验证集合是否出现相同数据
//                if (null == appReplenishmentListRes) {
//                    //无相同数据
//                    appReplenishmentListRes = new AppReplenishmentListRes();
//                    appReplenishmentListRes.setId(str.getGoodsId());
//                    appReplenishmentListRes.setNumber(str.getNumber());
//
//                    //查询商品
//                    GoodsInfo goodsInfoDO = goodsInfoService.selectById(str.getGoodsId());
//                    if (null != goodsInfoDO) {
//                        appReplenishmentListRes.setGoodsName(goodsInfoDO.getName());
//                        appReplenishmentListRes.setPicture(goodsInfoDO.getPicture());
//                    }
//                    appReplenishmentListRes.setTotal(nb);
//                    infoList.add(appReplenishmentListRes);
//                } else {
//                    //累加数量
//                    appReplenishmentListRes.setTotal(appReplenishmentListRes.getTotal() + nb);
//                }
//            }
//            return infoList;
//        }
//        return null;
    }
}
